package com.daka.service.impl;

import com.daka.dao.ActivitySignRecordDao;
import com.daka.entity.Activity;
import com.daka.entity.ActivitySign;
import com.daka.entity.ActivitySignRecord;
import com.daka.entity.Member;
import com.daka.enumerate.StatusCode;
import com.daka.service.*;
import com.daka.tools.DKQConstant;
import com.daka.tools.DateUtil;
import com.daka.tools.ServiceRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by yangx
 * CreateTime: 2016/9/18 16:40
 */

@Service("activitySignRecordService")
@Transactional
public class ActivitySignRecordServiceImpl implements ActivitySignRecordService {

    @Autowired
    private ActivitySignRecordDao activitySignRecordDao;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivitySignService activitySignService;
    @Autowired
    private MemberService memberService;


    @Override
    public int insert(ActivitySignRecord po) {
        return activitySignRecordDao.insert(po);
    }

    @Override
    public int update(ActivitySignRecord po) {
        return activitySignRecordDao.updateByPrimaryKeySelective(po);
    }

    @Override
    public ActivitySignRecord selectByPrimaryKey(Integer id) {
        return activitySignRecordDao.selectByPrimaryKey(id);
    }

    @Override
    public List<ActivitySignRecord> selectByStatement(ActivitySignRecord po) {
        return activitySignRecordDao.selectByStatement(po);
    }

    @Override
    public ActivitySign sign(String memberID, String activityCode, double lng, double lat){
        Member member = memberService.selectByMemberId(memberID);
        if(member==null){
            throw new ServiceRuntimeException(StatusCode.VOLUNTEER_NOT_EXISTS.getCode(),StatusCode.VOLUNTEER_NOT_EXISTS.getMessage());
        }
        Activity activity = activityService.selectByActCode(activityCode);
        if(activity==null){
            throw new ServiceRuntimeException(StatusCode.ACTIVITY_NOT_EXISTS.getCode(),StatusCode.ACTIVITY_NOT_EXISTS.getMessage());
        }
        //检查活动是否已被封存
        if(activity.getLocked() == DKQConstant.ACTIVITY_LOCK){
            throw new ServiceRuntimeException(StatusCode.ACTIVITY_IS_CLOSE.getCode(),StatusCode.ACTIVITY_IS_CLOSE.getMessage() + ",不可以打卡");
        }
        //活动开始前2小时或结束后4小时内都是有效签到
        String start = activity.getStartDay()+" "+activity.getStartHour()+":"+activity.getStartMinute()+":00";
        String end = activity.getEndDay()+" "+activity.getEndHour()+":"+activity.getEndMinute()+":00";
        int minutes = 0;
        try {
            //计算开始时间
            minutes = DateUtil.countMinutes2(DateUtil.getDate(),start);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(minutes>120){
            throw new ServiceRuntimeException(StatusCode.SIGN_NO_TIME_TO.getCode(),StatusCode.SIGN_NO_TIME_TO.getMessage());
        }
        try {
            //计算结束时间
            minutes = DateUtil.countMinutes2(end,DateUtil.getDate());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(minutes>240){
            throw new ServiceRuntimeException(StatusCode.SIGN_NO_TIME_TO.getCode(),StatusCode.SIGN_NO_TIME_TO.getMessage());
        }
        //活动未开始时，查询当前用户当前活动累计签到次数，不可以进行签退
        if(activity.getStatus() < DKQConstant.PROCEED_START){
            ActivitySignRecord activitySignRecord1 = new ActivitySignRecord();
            activitySignRecord1.setMember(Long.valueOf(member.getId()));
            activitySignRecord1.setActivity(Long.valueOf(activity.getId()));
            List<ActivitySignRecord> list1 = activitySignRecordDao.selectByStatement(activitySignRecord1);
            if(list1 != null && list1.size()>=1){
                throw new ServiceRuntimeException(StatusCode.ACTIVITY_NOT_START.getCode(),StatusCode.ACTIVITY_NOT_START.getMessage());
            }
        }
        //保存签到记录
        ActivitySignRecord activitySignRecord = new ActivitySignRecord();
        activitySignRecord.setActivity(Long.valueOf(activity.getId()));
        activitySignRecord.setMember(Long.valueOf(member.getId()));
        activitySignRecord.setLat(lat);
        activitySignRecord.setLng(lng);
        activitySignRecord.setCreatetime(DateUtil.getDate());
        activitySignRecord.setSignTime(DateUtil.getDate());
        activitySignRecordDao.insert(activitySignRecord);

        List<ActivitySignRecord> list = activitySignRecordDao.findByActivityAndVolunteer((long)activity.getId(),(long)member.getId());
        if (null == list){
            return null;
        }
        //若有2次以上的签到记录，则记录公益时间
        ActivitySign activitySign = new ActivitySign();

        //检查当前用户是否已在本次活动的公益记录
//        ActivitySign data = activitySignService.findByActivityAndVolunteer(member.getId(), activity.getId());
        activitySign.setMember(member.getId());
        activitySign.setActivityId(activity.getId());
        List<ActivitySign> list1 = activitySignService.selectByStatement(activitySign);
        ActivitySign data = list1.get(0);
        if(null != data && list.size() >=2){
            int times;
            int oldTime = data.getVolunteerTime();
            int targetTimes;//本次活动实际时长
            //计算两次签到时间的差
            String firstRecord = findFirstRecord(list);
            String lastRecord = findLastRecord(list);

            String startTime =  activity.getStartDay()+" "+activity.getStartHour()+":"+activity.getStartMinute();
            String endTime = activity.getEndDay()+" "+activity.getEndHour()+":"+activity.getEndMinute();

            try {
                targetTimes = DateUtil.countMinutes(startTime, endTime);
            } catch (Exception e) {
                throw new ServiceRuntimeException(StatusCode.SERVER_EXCEPTION.getCode(),"时间格式转换错误");
            }

            //若第一次签到时间在活动开始之前则是：最后一次签到时间-活动的开始时间；若第一次签到时间在活动开始之后，则是最后一次签到时间-第一次签到时间
            Date firstSign = DateUtil.str2Date(firstRecord,DateUtil.DATETIME_YYYY_MM_DD_HH_MM);
            Date actStartDate = DateUtil.str2Date(startTime,DateUtil.DATETIME_YYYY_MM_DD_HH_MM);

            if(firstSign.before(actStartDate)){
                try {
                    times = DateUtil.countMinutes(startTime, lastRecord);
                } catch (Exception e) {
                    throw new ServiceRuntimeException(StatusCode.SERVER_EXCEPTION.getCode(),"时间格式转换错误");
                }
                if(times>=targetTimes){
                    times = targetTimes;
                }
                System.out.println("第一次签到时间在活动开始之------前：" + times);
            }else{
                try {
                    times = DateUtil.countMinutes(firstRecord, lastRecord);
                } catch (Exception e) {
                    throw new ServiceRuntimeException(StatusCode.SERVER_EXCEPTION.getCode(),"时间格式转换错误");
                }
                if(times>=targetTimes){
                    times = targetTimes;
                }
                System.out.println("第一次签到时间在活动开始之------后：" + times);
            }

            Activity nowActivity = activityService.selectByPrimaryKey(activity.getId());
            if(times>0 && nowActivity.getStatus()>=DKQConstant.PROCEED_START)
            {
                System.out.println("本次是一次有效签出");
                data.setVolunteerTime(times);
                data.setRealTime(times);
                activitySign = activitySignService.updateTimes(data, oldTime);
                return activitySign;
            }
            return activitySign;
        }else{
//            Organization organization = organizationService.selectByPrimaryKey(activity.getOrganization());
            activitySign.setMember(member.getId());
            activitySign.setActivityId(activity.getId());
            activitySign.setUserType(DKQConstant.ROLES_VOLUNTEER);
            activitySign.setVolunteerTime(0);
            activitySign.setRealTime(0);
            activitySign.setCreateTime(DateUtil.getDate());
            activitySign.setDelStatus(DKQConstant.DEL_NO);
            activitySign.setVolunteerTimeStatus(1);//通过审核
            activitySign.setCommentType(DKQConstant.COMMENT_TYPE);

            activitySignService.insert(activitySign);
            return activitySign;
        }

    }


    /**
     * 获取第一次签到时间
     * @param list 签到列表
     * @return 签到时间
     */
    public String findFirstRecord(List<ActivitySignRecord> list){
        Date result = null;

        for(int i = 0; i < list.size();i++){
            if (i == 0){
                result = DateUtil.getDateFormString(list.get(0).getSignTime());
            }else {
                if( DateUtil.getDateFormString(list.get(i).getSignTime()).getTime() < result.getTime()){
                    result = DateUtil.getDateFormString(list.get(i).getSignTime());
                }
            }

        }
        return DateUtil.date2Str(result, DateUtil.DATETIME_YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 获取最后一次签到时间
     * @param list 签到列表
     * @return 签到时间
     */
    public String findLastRecord(List<ActivitySignRecord> list){
        Date result = null;

        for(int i = 0; i < list.size();i++){
            if (i == 0){
                result = DateUtil.getDateFormString(list.get(0).getSignTime());
            }else {
                if(DateUtil.getDateFormString(list.get(i).getSignTime()).getTime() > result.getTime()){
                    result = DateUtil.getDateFormString(list.get(i).getSignTime());
                }
            }

        }
        return DateUtil.date2Str(result, DateUtil.DATETIME_YYYY_MM_DD_HH_MM_SS);
    }


}







